package org.example.dao;

import org.example.model.Order;
import org.example.util.DBUtil;
import org.json.JSONArray;
import org.json.JSONObject;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class OrderDAOImpl implements OrderDAO {
    
    @Override
    public List<Order> findByUserId(Integer userId) {
        List<Order> orders = new ArrayList<>();
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        
        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT * FROM tb_order WHERE user_id = ? ORDER BY create_time DESC";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, userId);
            rs = pstmt.executeQuery();
            
            while (rs.next()) {
                Order order = new Order();
                order.setOrderId(rs.getInt("order_id"));
                order.setOrderNumber(rs.getString("order_number"));
                order.setUserId(rs.getInt("user_id"));
                order.setTotalAmount(rs.getDouble("total_amount"));
                order.setOrderStatus(rs.getString("order_status"));
                order.setCreateTime(rs.getTimestamp("create_time"));
                order.setPaymentTime(rs.getTimestamp("payment_time"));
                order.setShippingTime(rs.getTimestamp("shipping_time"));
                order.setReceiveTime(rs.getTimestamp("receive_time"));
                order.setCancelTime(rs.getTimestamp("cancel_time"));
                orders.add(order);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.closeAll(rs, pstmt, conn);
        }
        
        return orders;
    }

    @Override
    public Order findByOrderNumber(String orderNumber) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        Order order = null;
        
        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT * FROM tb_order WHERE order_number = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, orderNumber);
            rs = pstmt.executeQuery();
            
            if (rs.next()) {
                order = new Order();
                order.setOrderId(rs.getInt("order_id"));
                order.setOrderNumber(orderNumber);
                order.setUserId(rs.getInt("user_id"));
                order.setTotalAmount(rs.getDouble("total_amount"));
                order.setOrderStatus(rs.getString("order_status"));
                order.setCreateTime(rs.getTimestamp("create_time"));
                order.setPaymentTime(rs.getTimestamp("payment_time"));
                order.setShippingTime(rs.getTimestamp("shipping_time"));
                order.setReceiveTime(rs.getTimestamp("receive_time"));
                order.setCancelTime(rs.getTimestamp("cancel_time"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.closeAll(rs, pstmt, conn);
        }
        
        return order;
    }

    @Override
    public boolean updateOrderStatus(String orderNumber, String status) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        
        try {
            conn = DBUtil.getConnection();
            String sql = "UPDATE tb_order SET order_status = ? WHERE order_number = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, status);
            pstmt.setString(2, orderNumber);
            
            return pstmt.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            DBUtil.closeAll(null, pstmt, conn);
        }
    }

    @Override
    public boolean save(Order order) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        
        try {
            conn = DBUtil.getConnection();
            conn.setAutoCommit(false); // 开启事务
            
            String sql = "INSERT INTO tb_order (order_number, user_id, total_amount, order_status, create_time) " +
                        "VALUES (?, ?, ?, ?, NOW())";
            
            pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            pstmt.setString(1, order.getOrderNumber());
            pstmt.setInt(2, order.getUserId());
            pstmt.setDouble(3, order.getTotalAmount());
            pstmt.setString(4, order.getOrderStatus());
            
            int affectedRows = pstmt.executeUpdate();
            
            if (affectedRows == 0) {
                throw new SQLException("创建订单失败");
            }
            
            conn.commit();
            return true;
        } catch (Exception e) {
            try {
                if (conn != null) {
                    conn.rollback();
                }
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
            return false;
        } finally {
            DBUtil.closeAll(rs, pstmt, conn);
        }
    }

    @Override
    public boolean delete(Integer orderId) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        
        try {
            conn = DBUtil.getConnection();
            String sql = "DELETE FROM tb_order WHERE order_id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, orderId);
            
            return pstmt.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            DBUtil.closeAll(null, pstmt, conn);
        }
    }

    // 添加处理订单项的方法
    public boolean createOrderWithItems(Order order, JSONArray items) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        
        try {
            conn = DBUtil.getConnection();
            conn.setAutoCommit(false); // 开启事务
            
            // 保存订单主表
            System.out.println("开始创建订单: " + order.getOrderNumber());
            String sql = "INSERT INTO tb_order (order_number, user_id, total_amount, order_status, create_time) " +
                        "VALUES (?, ?, ?, ?, NOW())";
            
            pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            pstmt.setString(1, order.getOrderNumber());
            pstmt.setInt(2, order.getUserId());
            pstmt.setDouble(3, order.getTotalAmount());
            pstmt.setString(4, order.getOrderStatus());
            
            System.out.println("执行SQL: " + sql);
            System.out.println("参数: [" + order.getOrderNumber() + ", " + 
                order.getUserId() + ", " + order.getTotalAmount() + ", " + 
                order.getOrderStatus() + "]");
            
            int affectedRows = pstmt.executeUpdate();
            
            if (affectedRows == 0) {
                System.out.println("订单主表插入失败");
                throw new SQLException("创建订单失败");
            }
            
            rs = pstmt.getGeneratedKeys();
            int orderId;
            if (rs.next()) {
                orderId = rs.getInt(1);
                System.out.println("获取到订单ID: " + orderId);
            } else {
                System.out.println("未获取到订单ID");
                throw new SQLException("创建订单失败，未获取到ID");
            }
            
            // 插入订单详情
            sql = "INSERT INTO tb_order_detail (order_id, product_id, quantity, unit_price) VALUES (?, ?, ?, ?)";
            pstmt = conn.prepareStatement(sql);
            
            System.out.println("开始插入订单详情，商品数量: " + items.length());
            for (int i = 0; i < items.length(); i++) {
                JSONObject item = items.getJSONObject(i);
                pstmt.setInt(1, orderId);
                pstmt.setInt(2, item.getInt("productId"));
                pstmt.setInt(3, item.getInt("quantity"));
                pstmt.setDouble(4, item.getDouble("price"));
                pstmt.addBatch();
                
                System.out.println("添加商品到批处理: productId=" + item.getInt("productId") + 
                    ", quantity=" + item.getInt("quantity") + ", price=" + item.getDouble("price"));
                
                // 如果是从购物车购买，删除购物车中的商品
                if (item.has("cartId")) {
                    String cartId = item.getString("cartId");
                    System.out.println("删除购物车商品: cartId=" + cartId);
                    PreparedStatement deleteStmt = conn.prepareStatement(
                        "DELETE FROM tb_cart WHERE cart_id = ?"
                    );
                    deleteStmt.setString(1, cartId);
                    deleteStmt.executeUpdate();
                    deleteStmt.close();
                }
            }
            
            pstmt.executeBatch();
            
            // 更新商品库存
            sql = "UPDATE tb_product SET stock = stock - ? WHERE product_id = ?";
            pstmt = conn.prepareStatement(sql);
            
            System.out.println("开始更新商品库存");
            for (int i = 0; i < items.length(); i++) {
                JSONObject item = items.getJSONObject(i);
                pstmt.setInt(1, item.getInt("quantity"));
                pstmt.setInt(2, item.getInt("productId"));
                pstmt.addBatch();
                System.out.println("更新库存: productId=" + item.getInt("productId") + 
                    ", quantity=" + item.getInt("quantity"));
            }
            
            pstmt.executeBatch();
            
            conn.commit();
            System.out.println("订单创建成功，事务提交");
            return true;
            
        } catch (Exception e) {
            try {
                if (conn != null) {
                    conn.rollback();
                    System.out.println("发生错误，事务回滚: " + e.getMessage());
                }
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
            return false;
        } finally {
            DBUtil.closeAll(rs, pstmt, conn);
        }
    }
} 